package com.prj.ufdm.demo.tutorial.despatterns.structural.proxy.dynamicproxy;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

import com.prj.ufdm.demo.tutorial.despatterns.behavioral.strategy.SMSSend;
import com.prj.ufdm.demo.tutorial.despatterns.behavioral.strategy.SMSTelecom;

/**
 * DESC: 模拟JDK动态代理实现类 <br>
 * @author 胡义振
 * @date 2020年5月5日
 */
public class ProxyUtils {
	
	public static void main(String[] args) {
		SMSSend smsSend = new SMSTelecom();
		newProxyInstance(smsSend);
	}

	public static Object newProxyInstance(Object target) {
		
		StringBuffer contents = new StringBuffer();
		
		Class targetInfo = target.getClass().getInterfaces()[0];
		
		String targetInfoName = targetInfo.getSimpleName();
		contents.append(targetInfoName+"\n");
		String packerContent = "package com.prj.ufdm.demo.tutorial.despatterns.structural.proxy.dynamicproxy;";
		contents.append(packerContent+"\n");
		String importContent = "import " + targetInfo.getName() + ";";
		contents.append(importContent+"\n");
		String firstContent = "public class $Proxy implements "+ targetInfoName +"{";
		contents.append(firstContent+"\n");
		String fieldContent = "  private "+ targetInfoName +" target;";
		contents.append(fieldContent+"\n");
		contents.append("  public $Proxy("+targetInfoName+" target){" +"\n");
		contents.append("    this.target = target;" +"\n");
		contents.append("  }" +"\n");                         
		Method[] methods = targetInfo.getDeclaredMethods();
		String methodContent = "";
		for(Method method:methods) {
			contents.append("  public ");
			contents.append(method.getReturnType().getSimpleName());
			contents.append(" ");
			contents.append(method.getName());
			contents.append(" (");
			for(int i=0;i<method.getParameters().length;i++) {
				Parameter parameter = method.getParameters()[0];
				contents.append(parameter.getType().getSimpleName());
				contents.append(" "+parameter.getName());
				if(i<method.getParameters().length-1) {
				    contents.append(" ,");
				}
			}
			contents.append("){" + "\n");
			
			contents.append("  }" +"\n");
			method.getName();
		}
		
		contents.append(methodContent+"\n");
		
		contents.append("}"+"\n");
		
		System.out.println(contents.toString());
		
		return contents.toString();
	}
}
